package bma.common.json;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.TypeSerializer;
import org.codehaus.jackson.node.BaseJsonNode;
import org.codehaus.jackson.node.MissingNode;

import bma.common.langutil.core.ObjectUtil;

public class JEVNode extends BaseJsonNode {

	private JsonNode node;
	public String field;
	public int index;

	public JEVNode(String field) {
		super();
		this.field = field;
	}

	public JEVNode(int index) {
		super();
		this.index = index;
	}

	public JsonNode getNode() {
		return node;
	}

	public void setNode(JsonNode node) {
		this.node = node;
	}

	public boolean isUnknow() {
		return this.node == null;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	@Override
	public JsonToken asToken() {
		if (this.node != null)
			return this.node.asToken();
		return JsonToken.NOT_AVAILABLE;
	}

	@Override
	public boolean isMissingNode() {
		return this.node == null;
	}

	@Override
	public String asText() {
		if (this.node != null)
			return this.node.asText();
		return "";
	}

	@Override
	public int asInt(int defaultValue) {
		if (this.node != null)
			return this.node.asInt(defaultValue);
		return 0;
	}

	@Override
	public long asLong(long defaultValue) {
		if (this.node != null)
			return this.node.asLong(defaultValue);
		return 0L;
	}

	@Override
	public double asDouble(double defaultValue) {
		if (this.node != null)
			return this.node.asDouble(defaultValue);
		return 0.0;
	}

	@Override
	public JsonNode path(String fieldName) {
		if (this.node != null)
			return this.node.path(fieldName);
		return MissingNode.getInstance();
	}

	@Override
	public JsonNode path(int index) {
		if (this.node != null)
			return this.node.path(index);
		return this;
	}

	@Override
	public final void serialize(JsonGenerator jg, SerializerProvider provider)
			throws IOException, JsonProcessingException {
		jg.writeNull();
	}

	@Override
	public void serializeWithType(JsonGenerator jg,
			SerializerProvider provider, TypeSerializer typeSer)
			throws IOException, JsonProcessingException {
		jg.writeNull();
	}

	@Override
	public boolean equals(Object o) {
		if (this.node != null) {
			if (ObjectUtil.equals(this.node, o))
				return true;
		}
		return o == this;
	}

	@Override
	public String toString() {
		if (this.node != null) {
			return this.node.toString();
		}
		return "";
	}

}
